package com.mk.controller.user;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mk.constant.MessageConstant;
import com.mk.context.BaseContext;
import com.mk.entity.Chat;
import com.mk.entity.User;
import com.mk.result.Result;
import com.mk.service.IChatService;
import com.mk.service.IUserService;
import com.mk.vo.ChatVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 社区聊天相关业务
 */
@RestController
@RequestMapping("/user/chat")
@RequiredArgsConstructor
public class ChatController {

    private final IUserService userService;
    private final IChatService chatService;

    /**
     * 查询要聊天的好友是否存在
     * @param userId
     * @return
     */
    @CrossOrigin
    @GetMapping("/getUser")
    public Result<User> getUserInfo(Long userId) {
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error(MessageConstant.USER_UN_EXISTS);
        }
        return Result.success(user);
    }

    /**
     * 查找历史聊天记录
     * @param receiveUserId
     * @return
     */
    @CrossOrigin
    @GetMapping("/history/{receiveUserId}")
    public Result<List<ChatVO>> getChatHistory(@PathVariable Long receiveUserId) {
        Long sendUserId = BaseContext.getCurrentId();
        List<Chat> chatList = chatService.list(new LambdaQueryWrapper<Chat>()
                .eq(Chat::getSendUserId, sendUserId)
                .eq(Chat::getReceiveUserId, receiveUserId)
                .orderByAsc(Chat::getCreateTime)
                .select());
        return Result.success(BeanUtil.copyToList(chatList, ChatVO.class));
    }

}
